import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'index.dart';
import '../../../common/values/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/services/index.dart';
import '../../../common/widgets/index.dart';

/// 我的页面视图
/// 
/// 显示用户个人信息和相关功能入口
/// 包含用户头像、基本信息、功能菜单和退出登录等
/// 遵循GetX视图标准化结构
class MyIndexPage extends GetView<MyIndexController> {
  const MyIndexPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    // 定义红色
    final Color deeperRed = Color(0xFFB84040);
    
    return Column(
      children: [
        // 顶部按钮区域（左侧编辑按钮 + 右侧测试按钮[仅Debug模式]）
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(right: 12.0, top: 8.0, bottom: 0, left: 12.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // 左侧编辑按钮
              GestureDetector(
                onTap: controller.onEditProfileTap,
                child: Image.asset(
                  AssetsImages.bEditPng,
                  width: 32,
                  height: 32,
                ),
              ),
              // 右侧测试按钮（🔥 仅在Debug/测试版本显示）
              if (kDebugMode)
                GestureDetector(
                  onTap: controller.onTestTap,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.blue.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(
                        color: Colors.blue.withOpacity(0.3),
                        width: 1,
                      ),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.science_outlined,
                          size: 18,
                          color: Colors.blue,
                        ),
                        SizedBox(width: 4),
                        Text(
                          '测试',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.blue,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                )
              else
                // 占位符，保持布局一致（Release模式下显示空Container）
                SizedBox(width: 32, height: 32),
            ],
          ),
        ),
        // 内容区域
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                // 个人信息区
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 14.0),
                  child: Column(
                    children: [
                      // 用户头像、姓名等信息区域
                      GestureDetector(
                        onTap: controller.onAvatarTap,
                        child: Column(
                          children: [
                            // 🖼️ 头像（使用缓存组件）
                            CachedAvatar(
                              avatarUrl: controller.userAvatarUrl,
                              size: 80,
                            ),
                            const SizedBox(height: 10),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  controller.userDisplayName,
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(width: 6),
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                  decoration: BoxDecoration(
                                    color: deeperRed,
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  child: Text(
                                    controller.userLevelName,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 12,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 5),
                            Text(
                              '${controller.userCity} | ${controller.userSex} | ${controller.userAge}岁 ${controller.userSignature}',
                              style: TextStyle(
                                color: Colors.black54,
                                fontSize: 12,
                              ),
                              textAlign: TextAlign.center,
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 14),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Column(
                            children: [
                              Text(
                                FormatUtil.formatLikes(controller.userLikes),
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 17,
                                ),
                              ),
                              Text(
                                '点赞',
                                style: TextStyle(fontSize: 12),
                              ),
                            ],
                          ),
                          GestureDetector(
                            onTap: controller.onFollowersTap,
                            child: Column(
                              children: [
                                Obx(() {
                                  final friendCount = Get.find<UserService>().friendCount;
                                  return Text(
                                    friendCount.toString(),
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 17,
                                    ),
                                  );
                                }),
                                Text(
                                  '好友',
                                  style: TextStyle(fontSize: 12),
                                ),
                              ],
                            ),
                          ),
                          Column(
                            children: [
                              Text(
                                FormatUtil.formatPoints(controller.userPoints),
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 17,
                                ),
                              ),
                              Text(
                                '积分',
                                style: TextStyle(fontSize: 12),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                // 菜单卡片区
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 14.0),
                  child: Container(
                    decoration: BoxDecoration(
                      color: deeperRed,
                      borderRadius: BorderRadius.circular(14),
                    ),
                    child: Column(
                      children: [
                        _buildMenuItem(
                          AssetsImages.userPng,
                          '我的发布',
                          deeperRed,
                          onTap: controller.onMyPublishTap,
                        ),
                        // _buildMenuItem(
                        //   AssetsImages.userPng,
                        //   '活动申请用户管理',
                        //   deeperRed,
                        //   onTap: controller.onActivityApplicationTap,
                        // ),
                        _buildMenuItem(
                          AssetsImages.rechargePng,
                          '积分充值',
                          deeperRed,
                          onTap: controller.onFundsTap,
                        ),
                        _buildMenuItem(
                          AssetsImages.levelPng,
                          '等级和积分制度规则',
                          deeperRed,
                          onTap: controller.onLevelRulesTap,
                        ),
                        _buildMenuItem(
                          AssetsImages.securityPng,
                          '账号安全',
                          deeperRed,
                          onTap: controller.onSecurityTap,
                        ),
                        _buildMenuItem(
                          AssetsImages.supportPng,
                          '反馈与客服',
                          deeperRed,
                          onTap: controller.onFeedbackTap,
                        ),
                        _buildMenuItemWithStatus(
                          AssetsImages.idCardPng,
                          '实名认证',
                          deeperRed,
                          isVerified: controller.isRealNameVerified,
                          verificationText: controller.isRealNameVerified ? '已认证' : '未认证',
                          onTap: controller.onVerifyTap,
                        ),
                        _buildMenuItem(
                          AssetsImages.settingPng,
                          '设置',
                          deeperRed,
                          isLast: true,
                          onTap: controller.onSettingsTap,
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 22),
                // 退出登录按钮
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20.0),
                  child: SizedBox(
                    width: double.infinity,
                    height: 42,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.black87,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(21),
                        ),
                      ),
                      onPressed: () {
                        _showLogoutConfirmationDialog(Get.context!);
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '退出登录',
                            style: TextStyle(
                              fontSize: 15,
                              color: Colors.white,
                            ),
                          ),
                          SizedBox(width: 6),
                          Image.asset(
                            AssetsImages.loginoutPng,
                            width: 17,
                            height: 17,
                            color: Colors.white,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 22),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 显示退出登录确认对话框
  void _showLogoutConfirmationDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 30, horizontal: 20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '是否退出该账号。',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 30),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: SizedBox(
                        height: 44,
                        child: ElevatedButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.grey[200],
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            '取消',
                            style: TextStyle(
                              color: Colors.black87,
                              fontSize: 16,
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 15),
                    Expanded(
                      child: SizedBox(
                        height: 44,
                        child: ElevatedButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                            controller.onLogoutTap();
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Color(0xFFFAE05E),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            '确定',
                            style: TextStyle(
                              color: Colors.black87,
                              fontSize: 16,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  // 构建菜单项
  Widget _buildMenuItem(
    String imagePath,
    String title,
    Color backgroundColor, {
    bool isLast = false,
    Function()? onTap,
  }) {
    return Column(
      children: [
        ListTile(
          dense: true,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 14,
            vertical: 2,
          ),
          leading: Image.asset(
            imagePath,
            width: 22,
            height: 22,
            color: Colors.white,
          ),
          title: Text(
            title,
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
          trailing: Icon(
            Icons.chevron_right,
            color: Colors.white,
            size: 20,
          ),
          onTap: onTap,
        ),
        if (!isLast)
          Divider(height: 1, color: Colors.white24, indent: 14, endIndent: 14),
      ],
    );
  }
  
  // 构建带认证状态的菜单项
  Widget _buildMenuItemWithStatus(
    String imagePath,
    String title,
    Color backgroundColor, {
    bool isLast = false,
    bool isVerified = false,
    String? verificationText,
    Function()? onTap,
  }) {
    return Column(
      children: [
        ListTile(
          dense: true,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 14,
            vertical: 2,
          ),
          leading: Image.asset(
            imagePath,
            width: 22,
            height: 22,
            color: Colors.white,
          ),
          title: Text(
            title,
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (verificationText != null && verificationText.isNotEmpty)
                Text(
                  verificationText,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
              if (verificationText == null && isVerified)
                Text(
                  '已认证',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
              if ((verificationText != null && verificationText.isNotEmpty) || 
                  (verificationText == null && isVerified)) 
                SizedBox(width: 8),
              Icon(
                Icons.chevron_right,
                color: Colors.white,
                size: 20,
              ),
            ],
          ),
          onTap: onTap,
        ),
        if (!isLast)
          Divider(height: 1, color: Colors.white24, indent: 14, endIndent: 14),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MyIndexController>(
      init: MyIndexController(),
      id: "my_index",
      builder: (_) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            toolbarHeight: 0,
            backgroundColor: Colors.white,
            elevation: 0,
            systemOverlayStyle: SystemUiOverlayStyle(
              statusBarColor: Colors.white,
              statusBarIconBrightness: Brightness.dark,
              statusBarBrightness: Brightness.light,
            ),
          ),
          body: _buildView(),
        );
      },
    );
  }
}
